package com.sxx.mallAuth.controller;

import com.alibaba.fastjson.JSON;
import com.sxx.commons.constant.AuthConstant;
import com.sxx.commons.constant.SMSConstant;
import com.sxx.commons.exception.BizCodeEnum;
import com.sxx.commons.utils.R;
import com.sxx.commons.vo.MemberVO;
import com.sxx.mallAuth.feign.MemberFeignService;
import com.sxx.mallAuth.feign.ThirdPartFeignService;
import com.sxx.mallAuth.vo.LoginVO;
import com.sxx.mallAuth.vo.UserRegisterVO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: sunxx
 * @Date: 2024/8/13 - 08 - 13 - 19:52
 * @Description: com.sxx.mallAuth.controller
 * @version: 1.0
 */
@Controller
public class LoginController {

/*
    @GetMapping("/login.html")
    public String login(){
        return "login";
    }

    @GetMapping("/regist.html")
    public String regist(){
        return "regist";
    }
*/
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone")String phone){
        //防止60秒内重复发送
        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PREFIX + phone);
        if (redisCode != null && !"".equals(redisCode.toString())){
            long oldTime = Long.parseLong(redisCode.toString().split("_")[1]);
            if (System.currentTimeMillis() - oldTime <= 60000){
                //说明验证码发送间隔不足一分钟 提示
                return R.error(BizCodeEnum.VALID_SMS_EXCEPTION.getCode(), BizCodeEnum.VALID_SMS_EXCEPTION.getMsg());
            }
        }
        //生成随机验证码
//        String code = UUID.randomUUID().toString().substring(0, 5);code=15e20十六进制不可用
        Integer i = RandomUtils.nextInt();
        String code = i.toString().substring(0,5);
        thirdPartFeignService.sendSmsCode(phone,code);
        code = code +"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PREFIX+phone,code,5, TimeUnit.MINUTES);

        return R.ok();
    }

    /**
     * 注册
     * @param vo
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVO vo, BindingResult result, Model model){
        Map<String, String> map = new HashMap<>();
        if(result.hasErrors()){
            // 表示提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            model.addAttribute("error",map);
            return "/regist";
        }else {
            //验证码是否正确
            String code = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PREFIX + vo.getPhone());
            code = code.split("_")[0];
            if (!code.equals(vo.getCode())){
                //说明验证码不正确
                map.put("code","验证码错误");
                model.addAttribute("error",map);
                return "/regist";
            }else {
                //map.put("codeValue",code);//给前端code值进行实时校验..好像不行
                //验证码正确，删除验证码
                redisTemplate.delete(SMSConstant.SMS_CODE_PREFIX+vo.getPhone());
                //远程调用对应的服务，完成注册功能
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0){
                    //注册成功
                    return "redirect:http://auth.jiaxuanmall.asia:8051/login.html";
                }else {
                    //注册失败
                    map.put("msg",(String) r.get("msg"));
                    model.addAttribute("error",map);
                    return "/regist";
                }

            }
        }
    }

    @PostMapping("/login")
    private String login(LoginVO loginVO, RedirectAttributes redirectAttributes,
                         HttpSession session){
        R r = new R().put("msg", BizCodeEnum.USERNAME_PASSWORD_INVALID_EXCEPTION.getMsg());
        if (!StringUtils.isEmpty(loginVO.getUserName()) && !StringUtils.isEmpty(loginVO.getPassword())){
            r = memberFeignService.login(loginVO);
            if(r.getCode() == 0){
                String entityJson = (String) r.get("entity");
                //System.out.println("------------>"+entityJson);
                MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
                session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
                // 表示登录成功
                return "redirect:http://jiaxuanmall.asia:8070/index";
            }
        }
        redirectAttributes.addAttribute("errors",r.get("msg"));

        return "redirect:http://auth.jiaxuanmall.asia:8051/login.html";
    }
}
